<template>
  <view class="page_root" data-page-name="新建其他日报（定制）" data-page-identification="a_rguwr23liw">
    <!-- UNI_APP_EXEGESIS_START NAVIGATION_TEMPLATE UNI_APP_EXEGESIS_END -->
    <!-- begin vid_ivbdkd2yl0 自定义模板_shihqlccwh -->
    <view class="bgc-img"></view>
    <view class="body">
      <u-form :model="recordState" ref="recordForm" :rules="rules">
        <u-picker v-model="recordState.dateShow" mode="time" title="请选择工时提交日期" @confirm="onTimeConfirm" @cancel="onCancel"></u-picker>
        <u-form-item required="true" label-position="top" label="请选择工时提交日期" prop="dailyDate">
          <u-input border="true" placeholder="请选择工时提交日期" type="select" v-model:modelValue="recordState.dailyDate" @click="recordState.dateShow = true"></u-input>
        </u-form-item>
        <u-select v-model="recordState.projectCodeShow" mode="single-column" title="请选择工作类型" :list="recordState.projectCodeList" @confirm="onProjectConfirm"></u-select>
        <u-form-item required="true" label-position="top" label="工作类型" prop="projectCode">
          <u-input border="true" placeholder="请选择工作类型" type="select" v-model:modelValue="recordState.projectCode" @click="getProjectList"></u-input>
        </u-form-item>
        <u-form-item required="true" label-position="top" label="工时" prop="workingHours">
          <u-input type="number" border="true" placeholder="请输入工时(支持0.5的数字)" v-model:modelValue="recordState.workingHours"></u-input>
        </u-form-item>
        <u-form-item required="true" label-position="top" label="工作内容" prop="dailyContent">
          <u-input clearable="true" border="true" placeholder="请输入事项描述" v-model:modelValue="recordState.dailyContent"></u-input>
        </u-form-item>
      </u-form>
    </view>
    <u-row justify="space-around" style="margin-top: 24px">
      <u-col span="4">
        <u-button :custom-style="customStyle" @click="handlerCancel">取消</u-button>
      </u-col>
      <u-col span="4">
        <u-button :custom-style="customStyle" @click="handlerSubmit">保存</u-button>
      </u-col>
      <u-col span="4">
        <u-button :custom-style="customStyle" @click="handlerSubmitAndAdd">保存并新增</u-button>
      </u-col>
    </u-row>
    <!-- end vid_ivbdkd2yl0 自定义模板_shihqlccwh -->
  </view>
</template>
<script setup>

  import {
    ref,reactive,toRaw,markRaw,
    watch,computed,
    onBeforeMount,onMounted,onBeforeUnmount,onUnmounted,onActivated,onDeactivated,getCurrentInstance
  } from "vue";
  import { useRoute } from 'vue-router';
  const route = useRoute();
  import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
  import { cloneDeep, localGet, traversalTreeStructure, set, checkCaseCondition, throttle, merge, debounce, getGridStyle, getCellRenderAble, formulaStrategy } from '@/utils/index';
  import { isEqual, isNullOrEmpty, isEmptyArr, isArray, isEmpty, isNullOrUnDef, isContained } from '@/utils/is';
  import { CovertOptions, getChartsDataSourceConvert } from '@/utils/chart';
  import { propertyFormatByNumber, propertyFormatByPercentage, propertyFormatByDate } from '@/utils/format';
  import { FormFormat } from '@/utils/formFormat'
  import { customAddWaterMarkFunc, generateWaterMarkText } from '@/utils/addWaterMark';
  import dayjs from 'dayjs';
  import hashSum from 'hash-sum';
  /*** UNI_APP_EXEGESIS ***
  import { handleRedirect, permission, parseJson } from '@/utils/common';
  import { onPullDownRefresh, onLoad, onReady, onShow, onHide, onPageScroll, onUnload } from '@dcloudio/uni-app';
  import { BroadcastMessage } from '@/utils/BroadcastMessage';
  import { sendToken } from "@/hooks/useIframeToken";
  *** UNI_APP_EXEGESIS ***/


  // ---------------------------- 属性定义 ----------------------------
  const sourceId = "page50001907"

    // 是否显示菜单按钮
    const isMenuIconShow = false;
    // NAVIGATION_MENU
    const handleShowNavigation = ()=>{};

    let isProcessState = ref(false);


  const setTimeOutList = [];


      const vid_ivbdkd2yl0_props = reactive({
        code: "<view class=\"bgc-img\"></view>\n    <view class=\"body\">\n      <u-form :model=\"recordState\" ref=\"recordForm\" :rules=\"rules\">\n        <u-picker v-model=\"recordState.dateShow\" mode=\"time\" title=\"请选择工时提交日期\" @confirm=\"onTimeConfirm\" @cancel=\"onCancel\"></u-picker>\n        <u-form-item required=\"true\" label-position=\"top\" label=\"请选择工时提交日期\" prop=\"dailyDate\">\n          <u-input border=\"true\" placeholder=\"请选择工时提交日期\" type=\"select\" v-model:modelValue=\"recordState.dailyDate\" @click=\"recordState.dateShow = true\"></u-input>\n        </u-form-item>\n        <u-select v-model=\"recordState.projectCodeShow\" mode=\"single-column\" title=\"请选择工作类型\" :list=\"recordState.projectCodeList\" @confirm=\"onProjectConfirm\"></u-select>\n        <u-form-item required=\"true\" label-position=\"top\" label=\"工作类型\" prop=\"projectCode\">\n          <u-input border=\"true\" placeholder=\"请选择工作类型\" type=\"select\" v-model:modelValue=\"recordState.projectCode\" @click=\"getProjectList\"></u-input>\n        </u-form-item>\n        <u-form-item required=\"true\" label-position=\"top\" label=\"工时\" prop=\"workingHours\">\n          <u-input type=\"number\" border=\"true\" placeholder=\"请输入工时(支持0.5的数字)\" v-model:modelValue=\"recordState.workingHours\"></u-input>\n        </u-form-item>\n        <u-form-item required=\"true\" label-position=\"top\" label=\"工作内容\" prop=\"dailyContent\">\n          <u-input clearable=\"true\" border=\"true\" placeholder=\"请输入事项描述\" v-model:modelValue=\"recordState.dailyContent\"></u-input>\n        </u-form-item>\n      </u-form>\n    </view>\n    <u-row justify=\"space-around\" style=\"margin-top: 24px\">\n      <u-col span=\"4\">\n        <u-button :custom-style=\"customStyle\" @click=\"handlerCancel\">取消</u-button>\n      </u-col>\n      <u-col span=\"4\">\n        <u-button :custom-style=\"customStyle\" @click=\"handlerSubmit\">保存</u-button>\n      </u-col>\n      <u-col span=\"4\">\n        <u-button :custom-style=\"customStyle\" @click=\"handlerSubmitAndAdd\">保存并新增</u-button>\n      </u-col>\n    </u-row>",
    });



  // ============================ 属性定义 ============================

  // ---------------------------- 元素数据引用 ----------------------------
  // 组件 自定义模板_shihqlccwh ref 的引用
  const vid_ivbdkd2yl0_ref = ref(null);
  // 动态key的map
  const fieldTypeMap = {};
  // 动态key的map
  const refMap = {vid_ivbdkd2yl0_ref};

  const showState = reactive({
      vid_ivbdkd2yl0_visible: true,
  })
  // ============================ 元素数据引用 ============================

  // ---------------------------- 数据 ----------------------------


  // ============================ 数据 ============================

  // ---------------------------- 方法 ----------------------------
  // ---------------------------- 页面数据 ----------------------------


  // ============================ 页面数据 ============================

  // ---------------------------- 响应 ----------------------------

  // ============================ 响应 ============================

  // ---------------------------- 函数 ----------------------------

  // 自定义函数 返回上一页
  const customFunction_goBack_iw7h9p8j0q =  (...params) => {
    uni.navigateBack()
  }

  // ============================ 函数 ============================

  // ---------------------------- 页面参数 ----------------------------

  const pageParameter_state = reactive({
      'processInstanceId': undefined,
  })

  // ============================ 页面参数 ============================

  // ---------------------------- 组件事件处理方法 ----------------------------


  // ============================ 组件事件处理方法 ============================

  // ============================ 方法 ============================

  // ---------------------------- 生命周期 ----------------------------
  /*** UNI_APP_EXEGESIS ***
      // 获取上一层传递的数据
      const workflowChannel = new BroadcastMessage('WORKFLOW');
      workflowChannel.publish({ status: 'Ready' });
      workflowChannel.subscribe((data) => {
        if (data) {
          isProcessState.value = (window.self !== window.parent && data.type === 'hideHeader');
        }
      });
      *** UNI_APP_EXEGESIS ***/


  const pageScrollTop = ref(0)

  // *** PREVIEW_EXEGESIS ***
  onMounted(() => {
    setPageParams(route.query)
    // 设置表单的rule
    try{

    }catch{
        // do nothing
    }
  });
  // *** PREVIEW_EXEGESIS *** //

  /*** UNI_APP_EXEGESIS ***
  const routeOption = ref({})
  onLoad((option) => {
    routeOption.value = option;
  });
  onReady(() => {
    setPageParams(routeOption.value)
    // 设置表单的rule
    try{

    }catch{
        // do nothing
    }
  });
  // 图表刷新标记
  const uChartsReshowFlag = ref(false);
  onHide(() => { // 页面隐藏后标记置为false(如果不置为false无法触发图表更新)
      uChartsReshowFlag.value = false
  })
  onShow(() => {
      uChartsReshowFlag.value = true; // 页面激活后,标记置为true

      setPageParams(routeOption.value)
  })
  onPageScroll(e => {
      pageScrollTop.value = e.scrollTop
  });
  *** UNI_APP_EXEGESIS ***/

  const setPageParams = (routerParam)=>{
    const pageParams = [{"dataType":"STRING","dependencies":[],"name":"processInstanceId"}];
    const strategyMap = {
      STRING: (param, paramValue) => {
        pageParameter_state[param.name] = paramValue;
      },
      BOOLEAN: (param, paramValue) => {
        if('true' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = true
        } else if('false' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = false
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      NUMBER: (param, paramValue) => {
        if (!isNaN(paramValue)) {
          pageParameter_state[param.name] = Number(paramValue);
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      ARRAY: (param, paramValue) => {
        if (isNullOrUnDef(paramValue) || !paramValue || paramValue=== 'undefined') { // default value
          pageParameter_state[param.name] = [];
        } else if(paramValue.trim().startsWith('[') && paramValue.trim().endsWith(']')) {
          try {
            pageParameter_state[param.name] = JSON.parse(decodeURI(paramValue));
          } catch (error) {
            console.error('参数解析失败 ',error);
          }
        } else {
          console.error('参数传入错误！类型不匹配！');
        }
      },
    };
    pageParams.forEach((param) => {
      strategyMap[param.dataType](param, routerParam[param.name])
    });


  }

  onUnmounted(() => {
    // 销毁定时器
    setTimeOutList.forEach(({ repeat, timer }) => {
      repeat ?  clearInterval(timer): clearTimeout(timer);
    });
  });


  /*** UNI_APP_EXEGESIS ***
  onPullDownRefresh(() => {
    // 下拉刷新
    setTimeout(() => {
        uni.stopPullDownRefresh()
    }, 1000)
  })
  *** UNI_APP_EXEGESIS ***/

  // ============================ 生命周期 ============================

  // ---------------------------- 数据关联处理 ----------------------------
  // ---------------------------- 组件数据同步 ----------------------------

  // ============================ 组件数据同步 ============================
  //
  // ============================ 数据关联处理 ============================

  // ---------------------- 不同组件自定义的处理逻辑 ---------------------

  // ====================== 不同组件自定义的处理逻辑 ======================


  // ================================定制化逻辑========================================
  onMounted(() => {
      try {
        recordForm?.value?.setRules(rules);
        let appDiv = document.querySelector('#app')
        console.log(appDiv, 'adsdas');
        appDiv.style.background = 'linear-gradient(180deg, #E1EFFD 100%, #ffffff 0%)';
        let topHeader = document.querySelector('.uni-page-head');
        if (topHeader) topHeader.remove()
      } catch {
        // do nothing
      }

    });

    const recordForm = ref(null);
    const rules = {
      dailyDate: [
        { type: 'string', required: true, message: '请选择工时提交日期', trigger: ['blur', 'change'] },
      ],
      projectCode: [
        { type: 'string', required: true, message: '请选择工作类型', trigger: ['blur', 'change'] },
      ],
      workingHours: [
        {
          required: true,
          validator: validateWorkingHours,
          trigger: ['blur', 'change'],
        },
      ],
      dailyContent: [
        { type: 'string', required: true, message: '请输入事项描述', trigger: ['blur', 'change'] },
      ],
    };
    function validateWorkingHours(rule, value, callback) {
      if (!/^(0(\.5)?|[1-7](\.0|\.5)?|8(\.0)?)$/.test(value)) {
        callback(new Error('请输入有效的工时(支持0.5的数字)'));
      } else {
        callback();
      }
    }
    const customStyle = reactive({
      backgroundColor: '#21B5FF',
      color: '#fff',
    });
    // 定制化逻辑
    const recordState = reactive({
      isStage:false,
      dateShow: false,
      dailyDate: '',
      projectCodeShow: false,
      // 项目选择列表
      projectCodeList: [],
      // 选中的项目id
      projectCode: undefined,
      workingHours: null,
      dailyContent: '',
    });
    var currentURL = window.location.href;
    if (currentURL.includes("stage")) {
      recordState.isStage = true
    } else {
      recordState.isStage = false
    }
    // 时间框确定
    function onTimeConfirm(params) {
      recordState.dailyDate = `${params.year}-${params.month}-${params.day}`;
      getProjectList();
    }
    // 获取工作类型
    function getProjectList() {
      post('/solution-ppm/api/v2/built-in-system-ppm/jobCategory/jobCategoryList').then((data) => {
        recordState.projectCodeList = data.data.map((item) => {
          return {
            value: item.jobCategoryId,
            label: item.jobCategory,
          };
        });
        recordState.projectCodeShow = true;
      });
    }
    // 取消按钮
    function handlerCancel() {
      try {
        backHomePage();
        recordForm.value.resetFields();
      } catch (e) {
        console.log(e);
      }
    }
    // 保存日报
    function handlerSubmit() {
      recordForm.value.validate().then(() => {
        const params = {
          dailyDate: recordState.dailyDate,
          projectCode: recordState.projectCode,
          workingHours: recordState.workingHours,
          dailyContent: recordState.dailyContent,
        };
        post('/solution-ppm/api/v2/built-in-system-ppm/daily/add/weChat/PpmDaily', params).then(
          (data) => {
            if (data.code === 200) {
              uni.showToast({
                title: '保存成功',
                icon: 'success',
              });
              backHomePage();
            } else {
              uni.showToast({
                title: `${data.message}`,
                icon: 'error',
              });
            }
          },
        );
      });
    }
    // 保存并新增一条
    function handlerSubmitAndAdd() {
      recordForm.value.validate().then(() => {
        const params = {
          dailyDate: recordState.dailyDate,
          projectCode: recordState.projectCode,
          workingHours: recordState.workingHours,
          dailyContent: recordState.dailyContent,
        };
        post('/solution-ppm/api/v2/built-in-system-ppm/daily/add/weChat/PpmDaily', params).then(
          (data) => {
            if (data.code === 200) {
              uni.showModal({
                title: '保存成功',
                content: '可以继续填写下一条',
                showCancel: false, // 隐藏取消按钮
                confirmText: '确定',
                success: function (res) {
                  if (res.confirm) {
                    console.log('用户点击确定');
                    window.location.reload()
                  }
                },
              });
              //  recordState.dailyDate = '';
              //     recordState.projectCode = undefined;
              //     recordState.workingHours = null;
              //     recordState.dailyContent = '';
              // handleRedirect(`/pages/Page50001907/Page50001907?`)
            } else {
              uni.showToast({
                title: `${data.message}`,
                icon: 'error',
              });
            }
          },
        );
      });
    }
    const backHomePage = async () => {
      if (recordState.isStage === true) {
        window.location.href = 'https://ppm-stage.allintechinc.com/adv/adv-dpwtupxy-dwomi?type=page/'
      } else {
        window.location.href = 'https://ppm.allintechinc.com/adv/adv-dpwtupxy-dwomi?type=page/'
      }
    };
    // 工作类型确定
    function onProjectConfirm(params) {
      recordState.projectCode = params[0].label;
    }
</script>
<style lang="less" scoped>
  .page_root {
      min-height: 100%;
      box-sizing: border-box;
      padding-right: 16px;
      padding-bottom: 16px;
      padding-left: 16px;
      background-color:#3575C7;
  }


  .page_root {
        min-height: 100%;
        box-sizing: border-box;
        padding-right: 16px;
        padding-bottom: 16px;
        padding-left: 16px;
        background-color:#3575C7;
    }


    .page_root {
      min-height: 100%;
      box-sizing: border-box;
      padding-right: 16px;
      padding-bottom: 16px;
      padding-left: 16px;
      background: linear-gradient(180deg, #E1EFFD 100%, #ffffff 0%);
    }


    .body {
      height: 100%;
      padding: 12px;
      border-radius: 10px;
      background-color: #fff;
      position: relative;
      top: 15px;
    }

    .bgc-img {
      position: absolute;
      width: 100%;
      height: 300px;
      left: 0;
      top: -180px;
      background-image: url('http://10.40.0.33:9001/file-storage/416680575854426112.png');
      background-size: cover;
    }
</style>
